
//
//  DownloadHelper.m
//  Meach
//
//  Created by apple on 12-9-19.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DownloadHelper.h"

@implementation DownloadHelper

@synthesize appListFeedConnection, reqUrl, appListData;
- (id)initWithDelegate:(id <DownloadHelperDelegate>)theDelegate
{
    self = [super init];
    if (self != nil){
        delegate = theDelegate;
    }
    return self;
}

/*
 POST HTTP/1.1
 Host: XXX.XXX.XXX.XXX:XXXX
 Content-Type: multipart/related
 User-Agent: WIFI-JX
 Content-Length: 79
 
 <?xml version="1.0" encoding="utf-8"?><app_cmd cmd="0"/>
 */

-(void) startCmd: (NSString *)cmd code:(NSString*)code{
    NSString *serverAddrPath  = [[NSBundle mainBundle] pathForResource:@"serverAddr" ofType:@"xml"];
    NSData *data = [NSData dataWithContentsOfFile:serverAddrPath];
    NSString *serverIP = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSString *cmdPath  = [[NSBundle mainBundle] pathForResource:@"app_cmd" ofType:@"xml"];
    NSData *cmdData = [NSData dataWithContentsOfFile:cmdPath];
    NSString *cmdStr = [[NSString alloc] initWithData:cmdData encoding:NSUTF8StringEncoding];
    NSString *cmdContent = [cmdStr stringByAppendingFormat:@"<app_cmd cmd=\"%@\"/>", cmd];
    if (code) {
        cmdContent = [cmdContent stringByAppendingFormat:@"<app_data code=\"%@\"/>", code];//<app_data code="红外码" />
    }
    self.appListData = nil;
    self.reqUrl = [NSString stringWithFormat:@"http://%@/%@", serverIP, cmd];
    
    NSString *content = nil;
    if ([cmd intValue] == 0) {
        content = @"";
    }
    
    NSString *post = [[NSString alloc] initWithFormat:@"message=%@",@"hello,world."];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:reqUrl]];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"multipart/related" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setValue:@"WIFI-JX" forHTTPHeaderField:@"User-Agent"];
    [urlRequest setHTTPBody:postData];
    
    
    [serverIP release];
    [cmdStr release];
    [post release];
    
    
    [self.appListFeedConnection cancel];
    self.appListFeedConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    NSLog(@"startUrlRequest %@", self.reqUrl);
}

#pragma mark -
#pragma mark NSURLConnection delegate methods
- (void)handleError:(NSError *)error
{
    NSLog(@"%@", error);
    if (delegate && [delegate respondsToSelector:@selector(downloadErrorOccurred:)]) {
//        [delegate downloadErrorOccurred:error];
    }
}
//这里尤其要注意大小写问题：非常重要，当服务器把第一个参数设为小写的时候，传到客服端ios4.3.3手机第一个字母会变成大写，
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSHTTPURLResponse *httpResponse;
	httpResponse = (NSHTTPURLResponse *) response;
	assert([httpResponse isKindOfClass:[NSHTTPURLResponse class]]);
    NSDictionary *fields = [httpResponse allHeaderFields];
    //NSLog(@"allHeaderFields : %@", fields);
    self.appListData = [NSMutableData data];    // start off with new data
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [appListData appendData:data];  // append incoming data
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
    if ([error code] == kCFURLErrorNotConnectedToInternet)
    {
        // if we can identify the error, we can present a more precise message to the user.
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
                                                             forKey:NSLocalizedDescriptionKey];
        NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
                                                         code:kCFURLErrorNotConnectedToInternet
                                                     userInfo:userInfo];
        [self handleError:noConnectionError];
    }
    else
    {
        // otherwise handle the error generically
        [self handleError:error];
    }
    self.appListFeedConnection = nil;   // release our connection
}

// -------------------------------------------------------------------------------
//    connectionDidFinishLoading:connection
// -------------------------------------------------------------------------------
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.appListFeedConnection = nil;   // release our connection
    
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:appListData options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
    //NSLog(@"json: %@", json);

    if (delegate && [delegate respondsToSelector:@selector(didFinishDownload:)]) {
        [delegate didFinishDownload:json];
    }
    
    //NSString *jsonString  = [[NSString alloc] initWithData:appListData encoding:NSUTF8StringEncoding];
   // NSLog(@"DownloadHelper RECV: %@", jsonString);
    
}
-(void) cancelDownload{
    delegate = nil;
    [appListFeedConnection cancel];
}
// -------------------------------------------------------------------------------
//    dealloc
// -------------------------------------------------------------------------------
- (void)dealloc
{
    [super dealloc];
}


@end
